package com.common.android.ui.widget;

import android.content.Context;
import android.text.Selection;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.ViewDebug.ExportedProperty;
import android.widget.EditText;

/**
 * @ClassName SpenEditText
 * @Function 重写EditText，处理表情、at的ImageSpen在复制、剪切的选择时会选择错误情况，从而自定义的一个EditText类
 * @Reason
 * 
 * @author HuangYK
 * @version v1.3.2
 * @Date 2013 2013-12-12 下午6:43:06
 * 
 * @see
 */
public class SpenEditText extends EditText {

	private int mSelectionStar = 0;

	public SpenEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	@ExportedProperty(category = "text")
	public int getSelectionStart() {
		CharSequence content = getText();
		if (content instanceof Spanned) {
			mSelectionStar = ((Spanned) content)
					.getSpanStart(Selection.SELECTION_START);
			if (mSelectionStar + 1 == content.length()) {
				ImageSpan[] spans = getEditableText().getSpans(mSelectionStar,
						content.length(), ImageSpan.class);
				if (spans == null || spans.length <= 0) {
					return mSelectionStar;
				}
				String source = spans[spans.length - 1].getSource();
				int index = content.toString().lastIndexOf(source);
				if (index != -1
						&& (index + source.length() == content.length())) {
					mSelectionStar = index;
				}
			}
			return mSelectionStar;
		} else
			return -1;
	}

	@Override
	@ExportedProperty(category = "text")
	public int getSelectionEnd() {
		CharSequence content = getText();
		int selectionEnd = 0;
		if (content instanceof Spanned) {
			selectionEnd = ((Spanned) content)
					.getSpanEnd(Selection.SELECTION_END);
			ImageSpan[] spans = getEditableText().getSpans(mSelectionStar,
					content.length(), ImageSpan.class);
			if (spans == null || spans.length <= 0) {
				return selectionEnd;
			} else {
				if (mSelectionStar == selectionEnd - 1) {
					String source;
					for (ImageSpan span : spans) {
						source = span.getSource();
						if (mSelectionStar + source.length() > content.length())
							break;
						if (!TextUtils.isEmpty(source)
								&& source.equals(content.subSequence(
										mSelectionStar,
										mSelectionStar + source.length())
										.toString())) {
							return mSelectionStar + source.length();
						}
					}
				}
				return selectionEnd;
			}
		} else{
			return -1;
		}
	}
}
